<?php

namespace S3\Sample1Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use S3\Sample1Bundle\Entity\Connection;

/**
 * Default for sample application of presentation
 */
class DefaultController extends Controller
{
    public function indexAction($name)
    {
        return $this->render('S3Sample1Bundle:Default:index.html.twig', array('name' => $name));
    }
    
    /**
     * Test the basic controller that handles the param(s) to view
     * @return view object
     * @author Minh Ton <minh.ton@s3corp.com.vn>
     */
    public function testAction()
    {
        $paramA = 'parameter of string';
        return $this->render('S3Sample1Bundle:Default:test.html.twig', array(
            'paramA' => $paramA
        ));
    }
    
    /**
     * Test the controller with getting data from database and show to view
     * @author Minh Ton <minh.ton@s3corp.com.vn>
     * @return view object
     */
    public function testDatabaseAction()
    {
        $dataFromDatabase = '';
        $paramA = 'Database Testing';
        return $this->render('S3Sample1Bundle:Default:test_database.html.twig', array(
            'paramA' => $paramA
        ));
    }
    
    /**
     * Save connection to database
     * @return \Symfony\Component\HttpFoundation\Response
     * @author Minh Ton <minh.ton@s3corp.com.vn>
     */
    public function saveSimpleAction()
    {
        $connection = new Connection();
        $connection->setAccesstoken($accesstoken);
        $connection->setSecret($secret);
        
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($connection);
        $em->flush();
        return new Response('Connection is created');
    }
    
    /**
     * Get connections from the models
     * @author Minh Ton <minh.ton@s3corp.com.vn>
     */
    public function loadConnectionAction()
    {
        $ret = $this->getModelObject();
        #var_dump($arrResult);exit;
        return $this->render('S3Sample1Bundle:Default:listConnection.html.twig', array(
            'entities' => $ret['entities'],
            'find' => $ret['find'],
            'findOneById' => $ret['findOneById'],
            'findByProviderId' => $ret['findByProviderId'],
            'findBy' => $ret['findBy'],            
            'arrResult' => $ret['arrResult']
        ));
    }            
    
    private function getModelObject()
    {
        // find one record
        $id = 2;
        $find = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->find($id);        
        
        // get record by 1 attribute
        $findOneById = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->findOneById($id);
        $providerId = 2;
        $findByProviderId  = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->findByProviderid($providerId);
        
        // get record by many attributes
        $accessToken = 22;
        //$findByProviderIdAndAccessToken = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->findByProviderIdAndAccessToken($providerId, $accessToken);        
        $secret = 2;
        $findBy = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->findBy(array(
            'accesstoken' => $accessToken,
            'secret' => $secret
        ));
                
        // find list of records
        $findAll = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->findAll();       
                
        $arrResult = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->getConnectionArray($id);
        return array(
            'entities' => $findAll,
            'find' => $find,
            'findOneById' => $findOneById,
            'findByProviderId' => $findByProviderId,
            'findBy' => $findBy,            
            'arrResult' => $arrResult
        );
    }
    
    /**
     * Load sample form
     * @return type
     * @author Minh.Ton
     */
    public function addConnectionAction()
    {
        $connection = new \S3\Sample1Bundle\Entity\Connection();
        $form = $this->createForm(new \S3\Sample1Bundle\Form\ConnectionType(), $connection);        
        return $this->render('S3Sample1Bundle:Default:addConnection.html.twig', array(
            'form' => $form->createView()
        ));
    }
    
    /**
     * Save form
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return type
     */
    public function saveConnectionAction(\Symfony\Component\HttpFoundation\Request $request)
    {        
        $connection = new \S3\Sample1Bundle\Entity\Connection();
        $form = $this->createForm(new \S3\Sample1Bundle\Form\ConnectionType(), $connection);
        if($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            /*var_dump('form is valid or not');
            var_dump($form->isValid());exit;*/
            if($form->isValid())
            {
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($connection);
                $em->flush();
                
                $ret = $this->getModelObject();        
                $this->get('session')->setFlash('connection_msg', 'Form is saved!');
                return $this->render('S3Sample1Bundle:Default:listConnection.html.twig', array(            
                        'entities' => $ret['entities'],
                        'find' => $ret['find'],
                        'findOneById' => $ret['findOneById'],
                        'findByProviderId' => $ret['findByProviderId'],
                        'findBy' => $ret['findBy'],            
                        'arrResult' => $ret['arrResult']
                    ));
            }else{
                $this->get('session')->setFlash('connection_msg', 'Form is not saved!. Error happened.');
            }
        }                     
                
        return $this->render('S3Sample1Bundle:Default:addConnection.html.twig', array(
            'form' => $form->createView()
        ));
    }
    
    /**
     * Edit connection
     * @param type $id
     * @return type
     */
    public function editConnectionAction($id)
    {
        $connection = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->find($id);
        $form = $this->createForm(new \S3\Sample1Bundle\Form\ConnectionType(), $connection);
        
        // upload file
        //$request = $this->getRequest();

        //$editId = $request->get('editId');
        $editId = $id;
        if (!preg_match('/^\d+$/', $editId))
        {
            $editId = sprintf('%09d', mt_rand(0, 1999999999));
            //if ($posting->getId())
            if($connection->getId())
            {
                $this->get('punk_ave.file_uploader')->syncFiles(
                    array('from_folder' => 'attachments/' . $connection->getId(), //$posting->getId(), 
                      'to_folder' => 'tmp/attachments/' . $editId,
                      'create_to_folder' => true));
            }
        }
        
        $existingFiles = $this->get('punk_ave.file_uploader')->getFiles(array('folder' => 'tmp/attachments/' . $editId));
        
        return $this->render('S3Sample1Bundle:Default:editConnection.html.twig', array(
            'form' => $form->createView(),
            'entity' => $connection,
            'existingFiles' => $existingFiles
        ));
    }
    
    /**
     * Update connection
     * @param \Symfony\Component\HttpFoundation\Request $request
     * @return type
     */
    public function updateConnectionAction(\Symfony\Component\HttpFoundation\Request $request, $id)
    {
        $connection = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->find($id);
        $this->saveConnection($connection, $request);
        
        // for upload function        
        $fileUploader = $this->get('punk_ave.file_uploader');
        $fileUploader->syncFiles(
            array('from_folder' => '/tmp/attachments/' . $connection->getId(),
            'to_folder' => '/attachments/' . $connection->getId(),
            'remove_from_folder' => true,
            'create_to_folder' => true));
        
        $files = $fileUploader->getFiles(array('folder' => 'attachments/' . $connection->getId()));
        
        $entities = $this->getDoctrine()->getRepository('S3Sample1Bundle:Connection')->findAll();
        
        return $this->render('S3Sample1Bundle:Default:listConnection.html.twig', array(            
            'entities' => $entities
        ));
    }
    
    public function uploadAction($editId)
    {
        //$editId = $this->getRequest()->get('editId');
        if (!preg_match('/^\d+$/', $editId))
        {
            throw new Exception("Bad edit id");
        }

        $this->get('punk_ave.file_uploader')->handleFileUpload(array('folder' => 'tmp/attachments/' . $editId));
    }
    
    /**
     * Save connection for reusing in add and update functions
     * @param type $connection
     * @param type $request
     * @return type
     */
    private function saveConnection($connection, $request)
    {
        $form = $this->createForm(new \S3\Sample1Bundle\Form\ConnectionType(), $connection);
        if($request->getMethod() == 'POST')
        {
            $form->bindRequest($request);
            /*var_dump('form is valid or not');
            var_dump($form->isValid());exit;*/
            if($form->isValid())
            {
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($connection);
                $em->flush();
                $this->get('session')->setFlash('connection_msg', 'Form is saved!');
            }else{
                $this->get('session')->setFlash('connection_msg', 'Form is not saved!. Error happened.');
            }
        }        
    }
    
    /**
     * Create the custom form
     */
    public function simpleCustomFormAction()
    {                
        $form = $this->createFormBuilder(
                array(
                    'username' => 'minh.ton',                    
                    )
                )
                ->add('username', 'text', array('required' => true))
                ->add('password', 'password', array('required' => true))
                ->add('created_date', 'date', array('required' => true))
                ->getForm()
                ;
        return $this->render('S3Sample1Bundle:Default:custom_form.html.twig', array(
            'form' => $form->createView()
        ));
    }
    
    /**
     * create the user from the custom form
     * @param \Symfony\Component\HttpFoundation\Request $request
     */
    public function createUserAction(\Symfony\Component\HttpFoundation\Request $request)
    {
        $form = $this->createFormBuilder(
                array(
                    'username' => 'minh.ton',                    
                    )
                )
                ->add('username', 'text', array('required' => true))
                ->add('password', 'password', array('required' => true))
                ->add('created_date', 'date', array('required' => true))
                ->getForm()
                ;
        if($request->getMethod() == 'POST')
        {
            $form->bind($request);
            if($form->isValid())
            {
                var_dump('form is valid');
                var_dump($form->getData());
                var_dump($form->get('username')->getData());
                exit;
                //$form->getData();
                //$form->get('username')->getData();
                // execute or get the data and redirect to the list view
            }
        }
        var_dump('form is invalid');exit;
        return $this->render('S3Simple1Bundle:Default:custom_form.html.twig', array(
            'form' => $form->createView()
        ));
    }
    
    /**
     * Render a simple component
     * @param string $com_param
     */
    public function simpleComponentAction($com_param)
    {
        // execute the business logic
        return $this->render('S3Sample1Bundle:Default:_sampleComponent.html.twig', array(
            'param' => $com_param
        ));
    }
    
    /**
     * Example for calling a simple service
     */
    public function doSimpleServiceAction()
    {
        $newsletterManager = $this->get('newsletter_manager');
        $result = $newsletterManager->sendMail();
        var_dump($result);exit;
    }
    
    public function translateSimpleAction($name)
    {
        $trans1 = $this->get('translator')->trans('Symfony2 is great');
        $trans2 = $this->get('translator')->trans('Hello %name%', array('%name%' => $name));
        
        $trans3 = $this->get('translator')->transChoice(
                    'There is one apple|There are %count% apples',
                    10,
                    array('%count%' => 10)
                );
        
        $this->get('translator')->trans(
                    'Symfony2 is great', 
                    array(),
                    'messages',
                    'fr_FR'
                );
                
        
        return $this->render('S3Sample1Bundle:Default:translate_simple.html.twig', array(
            'trans1' => $trans1,
            'trans2' => $trans2,
            'trans3' => $trans3,
            'name' => 'minh.ton',
            'count' => 1
        ));
    }
}
